import { Result } from "@aspire/core";
import {
	CallHandler,
	ExecutionContext,
	Injectable,
	NestInterceptor,
} from "@nestjs/common";
import { HttpAdapterHost, Reflector } from "@nestjs/core";
import { Observable, map } from "rxjs";

@Injectable()
export class NormalizationInterceptor implements NestInterceptor {
	constructor(
		private reflector: Reflector,
		private adapterHost: HttpAdapterHost,
	) {}

	intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
		return next.handle().pipe(
			map((data) => {
				const nonResult = this.reflector.get<boolean>(
					"non-result",
					context.getHandler(),
				);
				if (nonResult) {
					return data;
				}
				const res = context.switchToHttp().getResponse();
				const adapter = this.adapterHost.httpAdapter;
				const contentType = adapter.getHeader(res, "Content-Type");
				const isAttachment = adapter.getHeader(res, "Content-Disposition");
				const isJSON = /(text|json)/i.test(contentType as string);
				if ((contentType && !isJSON) || isAttachment) {
					return data;
				}
				return {
					success: true,
					model: data,
					errCode: "",
					msg: "",
				} satisfies Result<any>;
			}),
		);
	}
}
